<template>
  <div class="pdf-preview">
    <div class="pdf-controls">
      <el-button @click="prevPage" :disabled="localCurrentPage <= 1">上一页</el-button>
      <span>第 {{ localCurrentPage }} 页 / 共 {{ localTotalPages }} 页</span>
      <el-button @click="nextPage" :disabled="localCurrentPage >= localTotalPages">下一页</el-button>
      <el-button @click="$emit('toggle-fullscreen')">
        {{ isFullscreen ? '退出全屏' : '全屏' }}
      </el-button>
      <el-input-number
        v-model="localCurrentPage"
        :min="1"
        :max="localTotalPages"
        @change="jumpToPage"
        size="mini"
      />
    </div>

    <pdf
      :src="src"
      :page="localCurrentPage"
      @num-pages="updateTotalPages"
      @page-loaded="updateCurrentPage"
    />
  </div>
</template>

<script>
import pdf from 'vue-pdf'

export default {
  components: { pdf },
  props: {
    fileUrl: String,
    currentPage: Number,
    totalPages: Number,
    isFullscreen: Boolean
  },
  data() {
    return {
      src: null,
      localCurrentPage: 1,
      localTotalPages: 0
    }
  },
  watch: {
    fileUrl: {
      immediate: true,
      async handler(url) {
        this.src = await pdf.createLoadingTask(url)
      }
    },
    currentPage: {
      immediate: true,
      handler(newVal) {
        this.localCurrentPage = newVal
      }
    }
  },
  methods: {
    updateTotalPages(totalPages) {
      this.localTotalPages = totalPages
      this.$emit('update:totalPages', totalPages) // 通知父组件更新 totalPages
    },
    updateCurrentPage(page) {
      this.localCurrentPage = page
      this.$emit('update:currentPage', page) // 通知父组件更新 currentPage
    },
    prevPage() {
      this.localCurrentPage = Math.max(1, this.localCurrentPage - 1)
    },
    nextPage() {
      this.localCurrentPage = Math.min(this.localTotalPages, this.localCurrentPage + 1)
    },
    jumpToPage(page) {
      this.localCurrentPage = Math.min(this.localTotalPages, Math.max(1, page))
    }
  }
}
</script>
